<?php
/**
 * Created by PhpStorm.
 * User: zcq
 * Date: 2018/10/16
 * Time: 15:32
 */

namespace app\admin\controller;


use app\admin\service\VoteItemsService;
use app\admin\service\VoteService;
use app\admin\service\VoteTypeService;
use PhpOffice\PhpSpreadsheet\Cell\DataType;
use PhpOffice\PhpSpreadsheet\Reader\Xlsx;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use function PHPSTORM_META\type;
use think\Db;
use think\Exception;
use think\Request;

class VoteItems extends Base
{
    public $itemsService;
    public $voteService;
    public $typeService;

    public function __construct(Request $request = null, VoteItemsService $voteItemsService, VoteService $voteService, VoteTypeService $voteTypeService)
    {
        parent::__construct($request);
        $this->itemsService = $voteItemsService;
        $this->voteService = $voteService;
        $this->typeService = $voteTypeService;
    }

    public function index()
    {
        $voteId = input('vote_id/d');
        $keyword = input('keyword');
        $type_id = input('type_id');
        $orderBy = input('order_by');
        $order = input('order');
        $vote = $this->check($voteId);
        $data = $this->itemsService->getPagination($voteId, $keyword, $type_id, $orderBy, $order);
        $type = $this->typeService->getList($voteId);
        $this->assign('type', $type);
        $this->assign('vote', $vote);
        $this->assign('data', $data);
        $this->assign('type_id', $type_id);
        $this->assign('keyword', $keyword);
        $this->assign('order_by', $orderBy);
        $this->assign('order', $order);
        return $this->fetch();
    }

    public function add()
    {
        $params = input();
        $vote = $this->check($params['vote_id'] ?? 0);
        if (\request()->isPost()) {
            $params['id'] = 0;
            $res = $this->itemsService->save($params);

            return dataReturn($res['code'], $res['msg']);
        }
        $this->assign('vote', $vote);
        $this->assign('url', url('add'));
        $this->assign('data', 1);
        $this->assign('title', '新增');
        $this->assign('vote_type', json_encode($this->typeService->getList($vote['id'])));
        return $this->fetch('info');
    }

    public function update()
    {
        $params = input();
        $id = input('id/d');
        $data = $this->itemsService->find($id);
        if (!$data) {
            $this->error('不存在');
        }
        $vote = $this->check($data['vote_id']);
        if (\request()->isPost()) {
            $res = $this->itemsService->save($params);

            return dataReturn($res['code'], $res['msg']);
        }
        $this->assign('vote', $vote);
        $this->assign('url', url('update'));
        $this->assign('data', json_encode($data));
        $this->assign('title', '编辑');
        $this->assign('vote_type', json_encode($this->typeService->getList($vote['id'])));
        return $this->fetch('info');
    }

    /**
     * 附件
     */
    public function attachment()
    {
        $id = input('id/d');
        $data = $this->itemsService->find($id);
        if (!$data) {
            $this->error('不存在');
        }
//        $attachment =
//        $this->assign('data',$data);
//        return $this->fetch();
    }

//    public function ajaxAdd()
//    {
//        $params = input();
//        $vote = $this->check($params['vote_id']??0);
//        $params['id'] = 0;
//        $res = $this->itemsService->save($params,$vote);
//        return dataReturn($res['code'],$res['msg']);
//    }

    public function ajaxUpdate()
    {
        $params = input();
        $res = $this->itemsService->updateByField($params);
        return dataReturn($res['code'], $res['msg']);
    }

    /**
     * 批量导入
     */
    public function batch()
    {
        $voteId = input('vote_id');
        $vote = $this->check($voteId);
        if (\request()->isPost()) {
            $param = input();
            $res = $this->itemsService->batch($param);
            if ($res['code']) {
                echo api_return(1, '成功添加' . $res['data'] . '条数据');
            } else {
                echo api_return(0, $res['msg']);
            }
            exit;
        }
        $this->assign('vote', $vote);
        return $this->fetch();
    }

    /**
     * 下载excel
     */
    public function downloadCount()
    {
        $voteId = input('vote_id/d');
        $vote = $this->check($voteId);

        $list = $this->itemsService->getList($voteId);

        $speadSheet = new Spreadsheet();
        $speadSheet->setActiveSheetIndex(0);
        $speadSheet->getActiveSheet()
            ->setCellValue('A1', '编号')
            ->setCellValue('B1', '名称')
            ->setCellValue('C1', '实际得票数')
            ->setCellValue('D1', '手动添加得票数')
            ->setCellValue('E1', '总票数')
            ->setCellValue('F1', '分类名称')
            ->setCellValue('G1', '备注');
        if ($list) {
            foreach ($list as $k => $v) {
                $speadSheet->getActiveSheet()
                    ->setCellValue('A' . ($k + 2), $v['mid'])
                    ->setCellValue('B' . ($k + 2), $v['name'])
                    ->setCellValue('C' . ($k + 2), $v['real'])
                    ->setCellValue('D' . ($k + 2), $v['extra'])
                    ->setCellValue('E' . ($k + 2), $v['total'])
                    ->setCellValue('F' . ($k + 2), $v['type_name'] ?? '')
                    ->setCellValue('G' . ($k + 2), $v['remark']);
            }
        }
        $filename = $vote['name'] . '.xlsx';
        header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
        header('Content-Disposition: attachment;filename="' . $filename . '"');
        header('Cache-Control: max-age=0');
        $writer = \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($speadSheet, 'Xlsx');
        $writer->save('php://output');
    }

    /**
     * 下载投票记录
     */
    public function downloadDataList()
    {
        $params = input();

        $ids = $params['ids'] ?? null;
        if (!$ids) {
            return dataReturn(0, '请选择一个');
        }
        $ids = explode(',', $ids);
        $data = $this->itemsService->getDataList($ids);

        if ($data) {
            $speadSheet = new Spreadsheet();
            foreach ($data as $key => $value) {
                if ($key) {
                    $speadSheet->createSheet();
                }
                $speadSheet->setActiveSheetIndex($key);
                $worksheet = $speadSheet->getActiveSheet();
                $sheetTitle = $value['mid'] ? $value['name'] . '(' . $value['mid'] . ')' : $value['name'];
                $worksheet->setTitle($sheetTitle);
                $worksheet->setCellValue('A1', '手机号码')
                    ->setCellValue('B1', 'IP地址')
                    ->setCellValue('C1', '投票数')
                    ->setCellValue('D1', '投票时间');
                if ($value['list']) {
                    foreach ($value['list'] as $k => $v) {
                        $worksheet->setCellValueExplicit('A' . ($k + 2), $v['mobile'], DataType::TYPE_STRING)
                            ->setCellValue('B' . ($k + 2), $v['ip'])
                            ->setCellValue('C' . ($k + 2), $v['nums'])
                            ->setCellValue('D' . ($k + 2), date('Y-m-d H:i', $v['addtime']));
                    }
                }
            }
        }
        $vote = $this->check($data[0]['vote_id']);
        $filename = $vote['name'] . '投票记录.xlsx';
        header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
        header('Content-Disposition: attachment;filename="' . $filename . '"');
        header('Cache-Control: max-age=0');
        $writer = \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($speadSheet, 'Xlsx');
        $writer->save('php://output');
    }

    public function check($voteId)
    {
        $vote = $this->voteService->check($voteId);
        if (!$vote)
            $this->error('不存在');
        return $vote;
    }

    public function ajax_del()
    {
        $voteId = input('vote_id/d');
        $id = input('id/d');
        $vote = $this->check($voteId);
        $res = $this->itemsService->del($voteId, $id);
        if ($res) {
            echo api_return(1, '删除成功');
        } else {
            echo api_return(0, '删除失败');
        }
    }


}